#include "EPSG/Scene.h"

#include "EPSG/Environ.h"
#include "EPSG/LightManager.h"
#include "EPSG/CameraManager.h"
#include "EPSG/Billboard.h"

/* System Includes */
#ifdef WIN32
#include <Windows.h>
#endif

/* OpenGL Includes */
#include <GL/GL.h>
#include <GL/GLU.h>

#include <stdio.h>

sigslot::signal1<EPSG::Scene*> EPSG::Scene::s_signalSceneLoaded;

EPSG::Scene::Scene( bool autoLoad /*= true */ )
{
	setBackColor( 0, 0, 0, 1 );
	_environ = NULL;
	_backfaceCulling = false;

	if( autoLoad )
		s_signalSceneLoaded.emit( this );
}

void EPSG::Scene::render()
{
	if( _backfaceCulling )
		glEnable( GL_CULL_FACE );

	glMatrixMode( GL_MODELVIEW );
	glPushMatrix();

	if( !EPSG::CameraManager::setupCamera() )
	{
		glPopMatrix();
		printf("\nCamera not set up");
		return;
	}
	if( EPSG::LightManager::setupLights() )
		glEnable( GL_LIGHTING );
	else
		glDisable( GL_LIGHTING );

	glClearColor( _color[0], _color[1], _color[2], _color[3] );
	glEnable( GL_DEPTH_TEST );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

	if( _environ != NULL )
		_environ->load();
	
	Group::render();

	if( _environ != NULL )
		_environ->unload();

	glMatrixMode( GL_MODELVIEW );
	glPopMatrix();

	if( _backfaceCulling )
		glDisable( GL_CULL_FACE );
}

void EPSG::Scene::setBackColor( float r, float g, float b, float a )
{
	_color[0] = r;
	_color[1] = g;
	_color[2] = b;
	_color[3] = a;
}

const EPSG::Vec4<float>& EPSG::Scene::getBackColor()
{
	return _color;
}

void EPSG::Scene::setEnviron( EPSG::Environ* e )
{
	_environ = e;
}

void EPSG::Scene::setBackfaceCulling( bool val )
{
	_backfaceCulling = val;
}

sigslot::signal1<EPSG::Scene*>& EPSG::Scene::getSignalSceneLoaded()
{
	return s_signalSceneLoaded;
}